package com.mijie.homi.admin.service.user;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mijie.homi.admin.dao.user.GradeDao;
import com.mijie.homi.common.domain.Grade;

@Service
public class GradeService {

	@Autowired
	private GradeDao dao;
	
	private Map<Integer,Integer[]> integralRangeCache = null;
	private Logger logger = Logger.getLogger(GradeService.class);
	
	public List<Grade> listGrade(){
		return dao.listGrade();
	}
	
	public int addGrade(Grade grade){
		integralRangeCache = null;
		return dao.addGrade(grade);
	}
	
	public int updateGrade(Grade grade){
		integralRangeCache = null;
		return dao.updateGrade(grade);
	}
	
	public Integer getCurrentHightGrade(){
		Integer grade = dao.getCurrentHightGrade();
		return grade==null?1:grade+1;
	}
	
	public Grade getRefGradeByIntegral(int integral){
		return dao.getRefGradeByIntegral(integral);
	}
	
	public Integer[] getIntegralRangeByGrade(int grade){
		if(integralRangeCache == null){
			List<Grade> list = listGrade();
			if(!list.isEmpty()){
				int lastGrade = 0;
				Integer lastIntegral = null;
				integralRangeCache = new HashMap<Integer,Integer[]>(list.size());
				Grade g = null;
				for(int i=0;i<list.size();i++){
					g = list.get(i);
					if(i==0){
						if(list.size()==1){
							integralRangeCache.put(g.getId(), new Integer[]{null,g.getIntegral()-1});
							break;
						}
					}else{
						integralRangeCache.put(lastGrade, new Integer[]{lastIntegral,g.getIntegral()-1});
						if(i==list.size()-1){
							integralRangeCache.put(g.getId(), new Integer[]{g.getIntegral(),null});
						}
					}
					lastGrade = g.getId();
					lastIntegral = g.getIntegral();
				}
			}
		}
		return integralRangeCache==null?null:integralRangeCache.get(grade);
	}
	
}
